package com.love_weinuo.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.love_weinuo.application.LoveApplication;

/**
 * Created by Administrator
 * on 2019/2/21.
 */


public class ToastUtil {

    private static Handler handler = new Handler(Looper.getMainLooper());

    private static Toast toast = null;

    private static final Object synObj = new Object();

    /**
     * 显示一个文本
     */
    public static void showToast(CharSequence msg) {
        showMessage(msg, Toast.LENGTH_SHORT);
    }

    public static void showT(){
        showMessage("联网失败", Toast.LENGTH_SHORT);
        LogUtil.e("联网失败");
    }

    /**
     * 资源文件方式显示文本
     */
    public static void showToast(int msg) {
        showMessage(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 显示一个文本
     */
    public static void showLongToast(CharSequence msg) {
        showMessage(msg, Toast.LENGTH_LONG);
    }

    /**
     * 资源文件方式显示文本
     */
    public static void showLongToast(int msg) {
        showMessage(msg, Toast.LENGTH_LONG);
    }

    /**
     * 显示一个文本并且设置时长
     */
    private static void showMessage(final CharSequence msg, final int len) {
        if (msg == null || msg.equals("")) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (synObj) { //加上同步是为了每个toast只要有机会显示出来
                    if (toast != null) {
                        //toast.cancel();
                        toast.setText(msg);
                        toast.setDuration(len);
                    } else {
                        toast = Toast.makeText(LoveApplication.getInstance().getApplicationContext(), msg, len);
                    }
                    toast.show();
                }
            }
        });
    }

    /**
     * 资源文件方式显示文本
     */
    private static void showMessage(final int msg, final int len) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (synObj) {
                    if (toast != null) {
                        toast.setText(msg);
                        toast.setDuration(len);
                    } else {
                        toast = Toast.makeText(LoveApplication.getInstance().getApplicationContext(), msg, len);
                    }
                    toast.show();
                }
            }
        });
    }

    public static void toLogin(final Context context){
      
    }

}
